package com.timo.lottery;

import lombok.extern.slf4j.Slf4j;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Timo
 * @Date: 2019/5/31 10:30
 * @Description: 类用途：
 */
@Slf4j
public class MathRandom {

    /**
     * Math.random()产生一个double型的随机数，判断一下 每个奖品出现的概率
     *
     * @return int
     *
     */
    public int PercentageRandom(List<Prize> prizes) {
        DecimalFormat df = new DecimalFormat("######0.00");
        int random = -2;
        try{
            double sumWeight = 0;
            //计算总权重
            for(Prize rp_1 : prizes){
                sumWeight += rp_1.getPrizeWeight();
            }
            double randomNumber;
            randomNumber = Math.random();
            System.out.println("randomNumber是：" + randomNumber);
            double d1 = 0;
            double d2 = 0;

            for(int i=0;i<prizes.size();i++){
                d2 += Double.parseDouble(String.valueOf(prizes.get(i).getPrizeWeight()))/sumWeight;
                if(i==0){
                    d1 = 0;
                }else{
                    d1 +=Double.parseDouble(String.valueOf(prizes.get(i-1).getPrizeWeight()))/sumWeight;
                }
                if(randomNumber >= d1 && randomNumber <= d2){
                    random = i;
                    System.out.println("d1是：" + d1);
                    System.out.println("d2是：" + d2);
                    break;
                }
            }
        }catch(Exception e){
            System.out.println(e.getMessage());
            log.error("生成抽奖随机数出错，出错原因：" + e.getMessage());
            random = -1;
        }
        return random;
    }

    /**
     * 测试主程序
     *
     * @param agrs
     */
    public static void main(String[] agrs) {
        int i = 0;
        MathRandom a = new MathRandom();
        List<Prize> prizes = new ArrayList();
        for(int m=0;m<3;m++){
            Prize rp = new Prize();
            rp.setPrizeAmount(10);//每个奖品数量设置10个
            rp.setPrizeWeight(1);//每个奖品的权重都设置成1，也就是每个奖品被抽到的概率相同（可根据情况自行设置权重）
            prizes.add(rp);
        }
        for (i = 0; i <= 100; i++)// 打印100个测试概率的准确性
        {
            System.out.println(a.PercentageRandom(prizes));
        }
    }
}